//
//  shangjiajianjieViewController.m
//  YeDian
//
//  Created by 罗西 on 3/28/16.
//  Copyright © 2016 罗西. All rights reserved.
//

#import "qiuzhixiangqingViewController.h"
#import "Tools.h"
#import "ConfigData.h"
#import "ASIFormDataRequest.h"
#import "AppDelegate.h"
#import "MBProgressHUD.h"
#import "Toast+UIView.h"
#import "JSON.h"
#import "UIButton+WebCache.h"
#import "NetManager.h"
#import "THud.h"
#import "UIImageView+WebCache.h"
#import "yedianxiangqingViewController.h"

@interface qiuzhixiangqingViewController ()<UITableViewDataSource,UITableViewDelegate>{
    int code;
    NSDictionary *myInfoDic;
    NSData *data;
    
}

@property (nonatomic,strong) UITableView *mainTableView;
@property (nonatomic,assign) BOOL isEditing;
@property (nonatomic,strong) NSString*  serverPath;
@property (nonatomic,strong) UIButton *imgBtn;
@property (nonatomic,strong) UIButton *btn;
@property (nonatomic,strong) NSString *avatar;
@property (nonatomic,strong) NSArray *imgArray;
@property (nonatomic,strong)    NSMutableArray *array2;
@property (nonatomic,strong) UIButton *phoneBtn;

@end

@implementation qiuzhixiangqingViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    NSLog(@"mmmmmmmmmmm:%@",_merchantId);
    self.title = @"求职详情";
    
    self.navigationItem.leftBarButtonItem.tintColor = [UIColor whiteColor];
    
    CGRect frame_img= CGRectMake(0,(44-19)/2,19,19);
    UIImageView* backView=[[UIImageView alloc] initWithFrame:frame_img];
    backView.image=[UIImage imageNamed:@"back2016"];
    CGRect frameBtn= CGRectMake(0, 0,50, 44);
    UIButton* homeBtn= [[UIButton alloc] initWithFrame:frameBtn];
    [homeBtn addTarget:self action:@selector(backFn) forControlEvents:UIControlEventTouchUpInside];
    [homeBtn addSubview:backView];
    UIBarButtonItem* barHomeBtn= [[UIBarButtonItem alloc] initWithCustomView:homeBtn];
    self.navigationItem.leftBarButtonItem=barHomeBtn;
    
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.mainTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-64) style:UITableViewStyleGrouped];
    [self.view addSubview:self.mainTableView];
    [self.mainTableView setDataSource:self];
    [self.mainTableView setDelegate:self];
    [self.mainTableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    [self.mainTableView setBackgroundColor:[UIColor colorWithRed:252/255.0 green:252/255.0 blue:252/255.0 alpha:1.0]];
    //self.view.backgroundColor = [UIColor whiteColor];
    
    
    _isEditing = NO;
    [self loadData];
    UIButton*  jubaoBtn=[[UIButton alloc] initWithFrame:CGRectMake(240, 5, 30, 34)];
    [jubaoBtn addTarget:self action:@selector(jubaoFn) forControlEvents:UIControlEventTouchUpInside];
    
    UILabel* jubaoLb=[[UILabel alloc] initWithFrame:CGRectMake(0, 0, 30, 34)];
    jubaoLb.text=@"举报";
    jubaoLb.font=[UIFont systemFontOfSize:14];
    jubaoLb.textColor=[UIColor whiteColor];
    jubaoLb.backgroundColor=[UIColor clearColor];
    [jubaoBtn addSubview:jubaoLb];
    
    
    
    [NSThread detachNewThreadSelector:@selector(loadData) toTarget:self withObject:nil];
    
    self.navigationItem.rightBarButtonItem=[[UIBarButtonItem alloc] initWithCustomView:jubaoBtn];
    
}
-(void)jubaoFn{
    [self.view makeToast:@"举报成功,我们的工作人员会尽快处理您反馈的信息" duration:1.0 position:@"center"];
}

-(void)editFn:(UIButton *)sender{
    if ([sender.titleLabel.text isEqualToString:@"编辑"]) {
        [sender setTitle:@"保存" forState:UIControlStateNormal];
        _isEditing = YES;
    }else{
        [sender setTitle:@"编辑" forState:UIControlStateNormal];
        [self doSaveOrderFn];
        _isEditing = NO;
    }
    [self.mainTableView reloadData];
}

-(void)backFn{
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)doSaveOrderFn{
    //kdType
    
    UITextField *tf1 = [self.view viewWithTag:101];
    UITextField *tf2 = [self.view viewWithTag:102];
    UITextField *tf3 = [self.view viewWithTag:106];
    
    NSUserDefaults*  ud=[[NSUserDefaults alloc] init];
    NSString *str = [ud objectForKey:@"uid"];
    NSLog(@"str:%@",str);
    
    NSString* loginURL=HOST;
    loginURL=[loginURL stringByAppendingString:@"/index.php/appMerchant/loadUserMerchantInfo"];
    NSLog(@"保存URL.loginURL==%@",loginURL);
    NSURL* url=[[NSURL alloc] initWithString:loginURL];
    ASIFormDataRequest *req=[ASIFormDataRequest requestWithURL:url];
    //
    [req addPostValue:tf1.text forKey:@"mp"];//快递类型
    [req addPostValue:tf2.text forKey:@"addr"];
    [req addPostValue:[myInfoDic objectForKey:@"name"] forKey:@"name"];
    [req addPostValue:[myInfoDic objectForKey:@"qm"] forKey:@"qm"];
    
    [req addPostValue:[myInfoDic objectForKey:@"name"] forKey:@"name"];
    [req addPostValue:tf3.text forKey:@"description"];
    
    if (self.serverPath.length != 0) {
        
        NSString* tmpImg=[NSString stringWithFormat:@"/upload/%@",self.serverPath];
        NSLog(@"tmpImg:%@",tmpImg);
        [req addPostValue:tmpImg forKey:@"pic0"];
        
    }
    
    
    
    
    
    
    
    NSString*  uid=[ud objectForKey:@"uid"];
    
    [req addPostValue:[NSString stringWithFormat:@"%@",uid] forKey:@"merchant_id"];
    [req startSynchronous];
    NSLog(@"req:%@",req);
    NSError *error = [req error];
    if (!error) {
        AppDelegate *app = (AppDelegate *)[UIApplication sharedApplication].delegate;
        [MBProgressHUD hideHUDForView:app.window animated:YES];
        
        NSString *response = [req responseString];
        NSLog(@"保存返回结果%@",response);
        NSDictionary* dic=[response JSONValue];
        code=[[dic objectForKey:@"code"] intValue];
        [self performSelectorOnMainThread:@selector(finishFn) withObject:nil waitUntilDone:YES];
    }
    
}

-(void)finishFn{
    if (code==1) {
        [self.view makeToast:@"保存资料成功" duration:1.0 position:@"center"];
        [self loadData];
        
    }else{
        [self.view makeToast:@"保存资料失败" duration:1.0 position:@"center"];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"showTab" object:nil];
    }
}

-(void)loadData{
    
    NSMutableDictionary *dic = [[NSMutableDictionary alloc]initWithDictionary:@{
                                                                                @"id":[NSString stringWithFormat:@"%@",_merchantId],
                                                                                }];
    [NetManager POST1DataWithParams:dic withUrl:@"/index.php/AppJobs/loadJobDetail" header:nil success:^(id object) {
        NSLog(@"---%@",object);
        //_commentArray = [NSMutableDictionary dictionaryWithDictionary:object];
        //_commentArray = [object objectForKey:@"list"];
        myInfoDic = (NSDictionary *)object;
        NSDictionary *dic = myInfoDic;
        _array2 = [NSMutableArray new];
        NSString *pic0 = [dic objectForKey:@"pic0"];
        NSString *pic1 = [dic objectForKey:@"pic1"];
        NSString *pic2 = [dic objectForKey:@"pic2"];
        NSString *pic3 = [dic objectForKey:@"pic3"];
        NSString *pic4 = [dic objectForKey:@"pic4"];
        if (pic0.length!=0) {
            NSString *str = [NSString stringWithFormat:@"%@/upload/%@",HOST,[dic objectForKey:@"pic0"]];
            [_array2 addObject:str];
        }
        if (pic1.length!=0) {
            NSString *str = [NSString stringWithFormat:@"%@/upload/%@",HOST,[dic objectForKey:@"pic1"]];
            [_array2 addObject:str];
        }
        if (pic2.length!=0) {
            NSString *str = [NSString stringWithFormat:@"%@/upload/%@",HOST,[dic objectForKey:@"pic2"]];
            [_array2 addObject:str];
        }
        if (pic3.length!=0) {
            NSString *str = [NSString stringWithFormat:@"%@/upload/%@",HOST,[dic objectForKey:@"pic3"]];
            [_array2 addObject:str];
        }
        if (pic4.length!=0) {
            NSString *str = [NSString stringWithFormat:@"%@/upload/%@",HOST,[dic objectForKey:@"pic4"]];
            [_array2 addObject:str];
        }
        
        [self.mainTableView reloadData];
        //[self loadData];
    } withAnimation:NO];
}

#pragma mark UITableViewDelegate/UITableViewDataSource

/**
 *  每个cell有多少行
 */
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return 1;
}


/**
 *  有多少个section
 */
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 4+_array2.count;
}

/**
 *  section的title
 */
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    
    return nil;
}

/**
 *  header的距离
 */
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return CGFLOAT_MIN;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    
    if(section == 1){
        return CGFLOAT_MIN;
    }
    return 10;
    
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    
    return nil;
}

/**
 *  row的高度
 */
-(CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        return 80;
    }else if (indexPath.section < 3){
        return 24;
    }else if (indexPath.section == 3){
        NSString *str = [myInfoDic objectForKey:@"desc"];
        if ([str isEqual:[NSNull null]]) {
            str = @"";
        }
        CGSize size = [self detailTextHeight:str size:CGSizeMake(SCREEN_WIDTH-60, CGFLOAT_MAX) font:[UIFont systemFontOfSize:13]];
        return 30+size.height+20;
    }else if (indexPath.section > 3){
        return SCREEN_WIDTH-40+20;
    }
    return 44;
}

/**
 *  cell的属性
 */
-(UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    UITableViewCell *cell = [UITableViewCell new];
    
    NSArray *array = @[@"职位",@"时间",@"求职详情"];
    NSArray *array2 = @[@"请输入电话",@"请输入地址"];
    UILabel *TitleLabel = [[UILabel alloc]initWithFrame:CGRectMake(30, 6, 30, 12)];
    if (indexPath.section == 0){
        UIImageView *imgView = [[UIImageView alloc]initWithFrame:CGRectMake(30, 10, 60, 60)];
        imgView.backgroundColor = [UIColor lightGrayColor];
        [imgView setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",HOST,[myInfoDic objectForKey:@"logo"]]] placeholderImage:[UIImage new]];
        [cell addSubview:imgView];
        imgView.backgroundColor = [UIColor lightGrayColor];
        
        NSString *str_qm = [myInfoDic objectForKey:@"qm"];
        NSString *str_name = [myInfoDic objectForKey:@"merchant_name"];
        
        if ([str_qm isEqual:[NSNull null]]||str_qm.length == 0) {
            str_qm = @"";
        }
        if ([str_name isEqual:[NSNull null]]||str_name.length == 0) {
            str_name = @"";
        }
        
        UILabel *nameLabel = [[UILabel alloc]initWithFrame:CGRectMake(110, 10, 200, 30)];
        nameLabel.text = [NSString stringWithFormat:@"%@",str_name];
        nameLabel.font = [UIFont systemFontOfSize:20];
        [cell addSubview:nameLabel];
        
        UILabel *nameLabel2 = [[UILabel alloc]initWithFrame:CGRectMake(110, 50, 200, 15)];
        NSString *str = [NSString stringWithFormat:@"%@",str_qm];
        nameLabel2.text = [NSString stringWithFormat:@"%@",str.length == 0?@"":str];
        nameLabel2.font = [UIFont systemFontOfSize:13];
        [cell addSubview:nameLabel2];
        
        UIButton *btn = [[UIButton alloc]initWithFrame:CGRectMake(SCREEN_WIDTH-90, 30, 70, 20)];
        btn.layer.borderColor = [UIColor orangeColor].CGColor;
        btn.layer.borderWidth = 1.0f;
        [cell addSubview:btn];
        [btn setTitle:@"已认证" forState:UIControlStateNormal];
        [btn setTitleColor:[UIColor orangeColor] forState:UIControlStateNormal];
        btn.titleLabel.font = [UIFont systemFontOfSize:12];
        btn.layer.cornerRadius = 10;
        
        //cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }else
    if(indexPath.section != 3 && indexPath.section<4){
        //TitleLabel.center = CGPointMake(TitleLabel.center.x, cell.center.y);
        TitleLabel.text = [array objectAtIndex:indexPath.section-1];
        TitleLabel.textColor = [UIColor redColor];
        TitleLabel.font = [UIFont systemFontOfSize:13];
        
    }
    [cell addSubview:TitleLabel];
    
    if (indexPath.section == 1 ||indexPath.section == 2){
        UITextField *tf = [[UITextField alloc]initWithFrame:CGRectMake(80, 5, 200, 14)];
        //tf.placeholder = [array2 objectAtIndex:indexPath.section-1];
        [cell addSubview:tf];
        tf.font = [UIFont systemFontOfSize:13];
        tf.userInteractionEnabled = _isEditing;
        if (_isEditing) {
            tf.layer.borderColor = [UIColor lightGrayColor].CGColor;
            tf.layer.borderWidth = 1.0f;
        }else{
            tf.layer.borderColor = [UIColor clearColor].CGColor;
            
        }
        
        if(indexPath.section == 1){
            tf.text = [myInfoDic objectForKey:@"reqJobName"];
            NSString *phone = [myInfoDic objectForKey:@"add_time"];
            if ([[myInfoDic objectForKey:@"mp"] isEqual:[NSNull null]]) {
                phone = @"";
            }
            _phoneBtn = [[UIButton alloc]initWithFrame:tf.frame];
            [_phoneBtn setTitle:phone forState:UIControlStateNormal];
            [_phoneBtn setTitleColor:[UIColor clearColor] forState:UIControlStateNormal];
            _phoneBtn.titleLabel.font = [UIFont systemFontOfSize:13];
            [_phoneBtn addTarget:self action:@selector(payPhone:) forControlEvents:UIControlEventTouchUpInside];
            //[cell addSubview:_phoneBtn];
        }else if (indexPath.section == 2){
            tf.text = [myInfoDic objectForKey:@"add_time"];
        }
        
        tf.tag = 100+indexPath.section;
    }else if(indexPath.section == 3){
        //        UITableViewCell *cel#import "NetManager.l = [tableView dequeueReusableCellWithIdentifier:@"ce"];
        //
        //        if (!cell) {
        //            cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"ce"];
        //
        
        UILabel * TitleLabel_ = [[UILabel alloc]initWithFrame:CGRectMake(30, 15, 80, 12)];
        TitleLabel_.text = @"求职详情";
        TitleLabel_.textColor = [UIColor redColor];
        TitleLabel_.font = [UIFont systemFontOfSize:13];
        [cell addSubview:TitleLabel_];
        
        NSString *str = [myInfoDic objectForKey:@"desc"];
        if ([str isEqual:[NSNull null]]) {
            str = @"";
        }
        CGSize size = [self detailTextHeight:str size:CGSizeMake(SCREEN_WIDTH-60, CGFLOAT_MAX) font:[UIFont systemFontOfSize:13]];
        UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(30, 30, SCREEN_WIDTH-60, size.height)];
        label.numberOfLines = 0;
        label.text = str;
        [cell addSubview:label];
        label.font = [UIFont systemFontOfSize:13];
        label.tag = 106;
        
//        UITextField *tf = [[UITextField alloc]initWithFrame:CGRectMake(30, 30, SCREEN_WIDTH-60, size.height)];
//        tf.placeholder = @"---";
//        [cell addSubview:tf];
//        tf.font = [UIFont systemFontOfSize:13];
//        [cell addSubview:tf];
//        tf.tag = 106;
//
//        tf.text = str;
//        tf.userInteractionEnabled = _isEditing;
        
        
        _btn = [[UIButton alloc]initWithFrame:CGRectMake(20, 70, SCREEN_WIDTH-40, (SCREEN_WIDTH-40))];
        _btn.layer.borderColor = [UIColor orangeColor].CGColor;
        //_btn.layer.borderWidth = 2.0f;
        NSString *strUrl = [NSString stringWithFormat:@"%@",[myInfoDic objectForKey:@"pic0"]];
        NSLog(@"section:%ld  strURL:%@",(long)indexPath.section,strUrl);
        [_btn sd_setImageWithURL:[NSURL URLWithString:strUrl] forState:UIControlStateNormal placeholderImage:[UIImage new]];
        [_btn addTarget:self action:@selector(paiZhaoFn) forControlEvents:UIControlEventTouchUpInside];
        //[btn setImageWithURL:[NSURL URLWithString:strUrl] forState:UIControlStateNormal placeholderImage:[UIImage new]];
        //btn.backgroundColor = [UIColor lightGrayColor];
        //[cell addSubview:_btn];
        _btn.userInteractionEnabled = _isEditing;
        //[cell.imageView sd_setImageWithURL:[NSURL URLWithString:strUrl] placeholderImage:[UIImage new]];
        return cell;
    }else if (indexPath.section > 3){
        _btn = [[UIButton alloc]initWithFrame:CGRectMake(20, 20, SCREEN_WIDTH-40, (SCREEN_WIDTH-40))];
        _btn.layer.borderColor = [UIColor orangeColor].CGColor;
        //_btn.layer.borderWidth = 2.0f;
        NSInteger index = indexPath.section-3;
        NSLog(@"x-x-x-x  :  %ld  index:%ld",(unsigned long)_array2.count,(long)index);
        NSString *strUrl = [NSString stringWithFormat:@"%@",_array2[index-1]];
        NSLog(@"section:%ld  strURL:%@",(long)indexPath.section,strUrl);
        [_btn sd_setImageWithURL:[NSURL URLWithString:strUrl] forState:UIControlStateNormal placeholderImage:[UIImage new]];
        [_btn addTarget:self action:@selector(paiZhaoFn) forControlEvents:UIControlEventTouchUpInside];
        //[btn setImageWithURL:[NSURL URLWithString:strUrl] forState:UIControlStateNormal placeholderImage:[UIImage new]];
        //btn.backgroundColor = [UIColor lightGrayColor];
        [cell addSubview:_btn];
        _btn.userInteractionEnabled = _isEditing;
        //[cell.imageView sd_setImageWithURL:[NSURL URLWithString:strUrl] placeholderImage:[UIImage new]];
        return cell;
    }
    
    return cell;
}

- (CGSize)detailTextHeight:(NSString *)text size:(CGSize)size font:(UIFont *)font {
    CGRect rectToFit = [text boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName: font} context:nil];
    return rectToFit.size;
}

-(void)payPhone:(UIButton *)sender{
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"tel://%@",(sender.titleLabel.text.length == 0?@"":sender.titleLabel.text)]]];
}

-(void)paiZhaoFn2{
    //_isAvatar = YES;
    [self paiZhaoFn];
}

-(void)addPhoto{
    //_isAvatar = NO;
    [self paiZhaoFn];
}

/**
 *  点击事件
 */
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (indexPath.section == 0) {
        NSDictionary *dic=myInfoDic;
        NSString* merchant_id=[dic objectForKey:@"uid"];
        yedianxiangqingViewController* ui=[[yedianxiangqingViewController alloc] init];
        ui.title = @"用户名片";
        ui.merchantId=[merchant_id intValue];
        [self.navigationController pushViewController:ui animated:NO];
    }
}

-(void)paiZhaoFn{
    
    
    
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0) {
        UIActionSheet *chooseImageSheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"拍照",@"相册", nil];
        [chooseImageSheet showInView:self.view];
        
    }else{
        // [[NSNotificationCenter defaultCenter] postNotificationName:@"paidanFn" object:nil];
        
        
        UIActionSheet *chooseImageSheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"拍照",@"相册", nil];
        [chooseImageSheet showInView:self.view];
    }
    
}
#pragma mark UIActionSheetDelegate Method
-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    
    UIImagePickerController * picker = [[UIImagePickerController alloc] init];
    picker.delegate = self;
    switch (buttonIndex) {
        case 0://Take picture
        
        [[NSNotificationCenter defaultCenter] postNotificationName:@"hideTab" object:nil];
        
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
            picker.sourceType = UIImagePickerControllerSourceTypeCamera;
            
        }else{
            NSLog(@"模拟器无法打开相机");
        }
        [self presentModalViewController:picker animated:YES];
        break;
        
        case 1://From album
        [[NSNotificationCenter defaultCenter] postNotificationName:@"hideTab" object:nil];
        picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        [self presentModalViewController:picker animated:YES];
        break;
        
        default:
        //[self dismissModalViewControllerAnimated:YES];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"showTab" object:nil];
        break;
    }
}

#pragma 拍照选择照片协议方法
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    
    [UIApplication sharedApplication].statusBarHidden = YES;
    NSString *type = [info objectForKey:UIImagePickerControllerMediaType];
    //当选择的类型是图片
    if ([type isEqualToString:@"public.image"])
    {
        //先把图片转成NSData
        UIImage* image = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
        CGSize newSize=CGSizeMake(160, 160);
        newSize=CGSizeMake(SCREEN_WIDTH-40, SCREEN_WIDTH-40);
        image=[self smallImg:image scaledToSize:newSize];
        
        if (UIImagePNGRepresentation(image) == nil)
        {
            data = UIImageJPEGRepresentation(image, 1.0);
        }
        else
        {
            data = UIImagePNGRepresentation(image);
        }
        
        //图片保存的路径
        //这里将图片放在沙盒的documents文件夹中
        NSString * DocumentsPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
        
        //文件管理器
        NSFileManager *fileManager = [NSFileManager defaultManager];
        
        //把刚刚图片转换的data对象拷贝至沙盒中 并保存为image.png
        [fileManager createDirectoryAtPath:DocumentsPath withIntermediateDirectories:YES attributes:nil error:nil];
        [fileManager createFileAtPath:[DocumentsPath stringByAppendingString:@"/image.jpg"] contents:data attributes:nil];
        
        //得到选择后沙盒中图片的完整路径
        NSString* filePath = [[NSString alloc]initWithFormat:@"%@%@",DocumentsPath,  @"/image.jpg"];
        NSLog(@"filePath:%@",filePath);
        
        
        self.avatar=filePath;
        
        //关闭相册界面
        [picker dismissViewControllerAnimated:YES completion:nil];
        //[picker dismissModalViewControllerAnimated:YES];
        
        //创建一个选择后图片的小图标放在下方
        //类似微薄选择图后的效果
        
        
        [[NSNotificationCenter defaultCenter] postNotificationName:@"showTab" object:nil];
        
        [self savePhotoFn];
        
    }
}

-(void)savePhotoFn{
    //NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    
    NSString* uploadURL=@"yw_uploadify.php";
    uploadURL=[HOST stringByAppendingString:uploadURL];
    
    //NSLog(@"uploadURL=%@",uploadURL);
    ASIFormDataRequest *request = [[ASIFormDataRequest alloc] initWithURL:[NSURL URLWithString:uploadURL]];
    
    NSDate* now = [NSDate date];
    NSDateFormatter* fmt = [[NSDateFormatter alloc] init];
    fmt.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"];
    
    fmt.dateFormat = @"yyyyMMddHHmmss";
    NSString* dateString = [fmt stringFromDate:now];
    NSLog(@"%@", dateString);
    
    
    self.serverPath=[Tools md5:dateString];
    
    
    
    
    [request setPostValue:[NSString stringWithFormat:@"%@",self.serverPath] forKey:@"serverImgName"];
    
    NSLog(@".....serverPath=%@", self.serverPath);
    
    self.serverPath=[self.serverPath stringByAppendingString:@".jpg"];
    
    [request setFile:self.avatar  forKey:@"filename"];
    
    
    
    //[request setValue:uid forKey:@"uid"];
    request.delegate = self;
    //
    AppDelegate *app = (AppDelegate *)[UIApplication sharedApplication].delegate;
    [[MBProgressHUD showHUDAddedTo:app.window animated:YES] setLabelText:@"正在处理中，请稍后..."];
    
    
    
    
    [request startAsynchronous];
    
    
    [self savrMyAvatarFn];
}

-(void)savrMyAvatarFn{
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    NSString *uid=[userDefaults objectForKey:@"uid"];
    NSString* strFlag=[userDefaults objectForKey:@"flag"];
    int flag=[strFlag intValue];
    
    [self.view makeToast:@"照片保存成功!"
                duration:1.0
                position:[NSValue valueWithCGPoint:CGPointMake(160, 210)]
     ];
    //NSDictionary* dic=[NSDictionary dictionaryWithObject:self.avatar forKey:@"avatar"];
    
    
    
    AppDelegate *app = (AppDelegate *)[UIApplication sharedApplication].delegate;
    [MBProgressHUD hideHUDForView:app.window animated:YES];
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"showTab" object:nil];
    
    //if(!_isAvatar)
    {
        NSUserDefaults*  ud=[[NSUserDefaults alloc] init];
        NSUserDefaults *accountDefaults = [NSUserDefaults standardUserDefaults];
        NSString* mp_ = [accountDefaults objectForKey:@"phone"];
        //NSString* mp_=[ud objectForKey:@"mp"];
        if (!mp_) {
            return;
        }
        NSLog(@"mp:%@",mp_);
        NSString* loginURL=HOST;
        loginURL=[loginURL stringByAppendingString:@"index.php/UserImg/saveImg"];
        NSLog(@"保存URL.loginURL==%@",loginURL);
        NSURL* url=[[NSURL alloc] initWithString:loginURL];
        ASIFormDataRequest *req=[ASIFormDataRequest requestWithURL:url];
        
        NSString*  uid2=[ud objectForKey:@"uid"];
        
        [req addPostValue:[NSString stringWithFormat:@"%@",uid2] forKey:@"uid"];
        
        NSString* tmpImg=[NSString stringWithFormat:@"%@",self.serverPath];
        NSLog(@"tmpImg:%@",tmpImg);
        [req addPostValue:[NSString stringWithFormat:@"/upload/%@",tmpImg] forKey:@"img_path"];
        
        [req startSynchronous];
        NSError *error = [req error];
        
        
        if (!error) {
            AppDelegate *app = (AppDelegate *)[UIApplication sharedApplication].delegate;
            [MBProgressHUD hideHUDForView:app.window animated:YES];
            
            NSString *response = [req responseString];
            NSLog(@"保存返回结果%@",response);
            myInfoDic=[response JSONValue];
            NSString* uid=[myInfoDic objectForKey:@"uid"];
            NSLog(@"ID%@",uid);
            
            
            //[self.mainTableView reloadData];
            [self loadData];
            //[self performSelectorOnMainThread:@selector(finishLoadMyInfoFn) withObject:nil waitUntilDone:YES];
        }else{
            NSLog(@"move failed:%@", [error localizedDescription]);
        }
    }
    
    
}

-(UIImage*)smallImg:(UIImage*)image scaledToSize:(CGSize)newSize
{
    UIGraphicsBeginImageContext(newSize);
    [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
